﻿using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using ERP.Production.ProductionManagement.Dtos;
using ERP.ERPModels.Production.ProductionManagement;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories;
using System;
using System.IO;
using System.Text;

namespace ERP.Web.Controllers.ProductionManagement
{
    // 提供两种路由方式，同时支持 /ProductionWaste 和 /ProductionManagement/ProductionWaste
    [Route("[controller]")]
    [Route("ProductionManagement/[controller]")]
    public class ProductionWasteController : Controller
    {
        private readonly IRepository<ProductionWaste, int> _wasteRepository;

        public ProductionWasteController(IRepository<ProductionWaste, int> wasteRepository)
        {
            _wasteRepository = wasteRepository;
        }

        [HttpGet]
        [HttpGet("Index")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取生产废料分页列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        [HttpPost("GetList")]
        public async Task<JsonResult> GetList([FromBody] GetProductionWasteDTO dto)
        {
            // 创建查询
            var query = await _wasteRepository.GetQueryableAsync();

            // 应用筛选条件
            if (!string.IsNullOrWhiteSpace(dto.WasteOrderNumber))
            {
                query = query.Where(x => x.WasteOrderNumber.Contains(dto.WasteOrderNumber));
            }

            if (!string.IsNullOrWhiteSpace(dto.ProductionOrder))
            {
                query = query.Where(x => x.ProductionOrder.Contains(dto.ProductionOrder));
            }

            // 获取总记录数
            var totalCount = await query.CountAsync();

            // 应用排序
            query = query.OrderBy(x => x.Id);

            // 应用分页
            int pageSize = dto.PageSize > 0 ? dto.PageSize : 10;
            int pageIndex = dto.PageIndex > 0 ? dto.PageIndex : 1;
            var list = await query.Skip((pageIndex - 1) * pageSize)
                                .Take(pageSize)
                                .ToListAsync();

            // 返回结果
            return Json(new
            {
                code = 0,
                msg = "success",
                count = totalCount,
                data = list
            });
        }
    }
}